<template>
  <div v-loading="loading" class="container">
    <!--    <i class="el-icon-full-screen fullBtn" @click="fullScreen" />-->
    <gantt
      v-if="showGantt"
      ref="ganttComponents"
      class="left-container"
      :tasks="tasks"
      :business-id="currentDealId"
      @task-updated="logTaskUpdate"
      @link-updated="logLinkUpdate"
      @task-selected="selectTask"
      @addHandler="addHandler"
    />

    <!-- 添加或修改项目-督办事项对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <dealSuperviseForm ref="dealSuperviseForm" @submitFormEnd="submitFormEnd" />
    </el-dialog>
  </div>
</template>

<script>
import dealSuperviseForm from '@/views/saas/kaihui/supervise/kaiHuiSuperviseForm.vue'
import Gantt from '@/views/saas/kaihui/supervise/dhtmlxGantt/kaiHuiGantt.vue'
import { ganttChartData, updateTimeByRowId, saveDealSupervise, delDealSupervise, updateLieByRowId } from '@/api/sass/kaihui/supervise/kaiHuiSupervise'

export default {
  components: { Gantt, dealSuperviseForm },
  filters: {
    toPercent(val) {
      if (!val) {
        return '0'
      }
      return Math.round((+val) * 100)
    },
    niceDate(obj) {
      return `${obj.getFullYear()} / ${obj.getMonth() + 1} / ${obj.getDate()}`
    }
  },
  data() {
    return {
      drawer: false,
      loading: false,
      showGantt: false,
      title: '督办事项',
      formOpen: false,
      tasks: {
        data: [],
        links: []
      },
      selectedTask: null,
      messages: [],
      currentDealId: undefined
    }
  },
  watch: {
  },
  created() {
  },
  methods: {
    /**
     * 初始化数据
     * 甘特图组件使用方法,
     * 1.现根据ganttTable给出的查出指定数据.
     * 2.新写个页面. 将数据传递过去.  加个updateHandler.点击甘特图的时候会调用 list页面上的这个方法进行修改或查看
     */
    init(dealId) {
      // 初始化销毁甘特图
      this.currentDealId = dealId
      if (dealId !== undefined && dealId !== '' && dealId !== null) {
        this.loading = true
        this.showGantt = false
        ganttChartData(dealId).then(response => {
          var ganttData = []
          var ganttLine = []
          if (response.data !== null && response.data !== undefined) {
            response.data.forEach((item, index) => {
              ganttData.push({
                id: item.rowId,
                text: item.label,
                start_date: item.start,
                duration: item.duration,
                progress: item.isItDone,
                toolTipsTxt: this.$t('参与人') + ': ' + item.participants,
                open: true,
                type: index,
                parent: item.parentId,
                rowId: item.rowId,
                principal: item.principal,
                dealId: item.dealId,
                remark: item.remark
              })
              const lineTemp = JSON.parse(item.ganttLine)
              if (this.isBlack(lineTemp) && this.isBlack(lineTemp.source) && this.isBlack(lineTemp.target)) {
                // 线数据
                ganttLine.push({
                  id: this.isBlack(lineTemp.id) ? index : lineTemp.id,
                  source: lineTemp.source,
                  target: lineTemp.target,
                  type: this.isBlack(lineTemp.type === undefined) ? '1' : lineTemp.type
                })
              }
            })
          }
          this.$nextTick(() => {
            this.showGantt = true
            this.tasks.data = ganttData
            this.tasks.links = ganttLine
          })
          this.loading = false
        })
      }
    },
    isBlack(val) {
      return val !== undefined && val !== null && val !== ''
    },
    // 全屏
    fullScreen() {
      this.$nextTick(() => {
        this.$refs.ganttComponents.fullScreen()
      })
    },
    selectTask(task) {
      this.selectedTask = task
    },

    addMessage(message) {
      this.messages.unshift(message)
      if (this.messages.length > 40) {
        this.messages.pop()
      }
    },
    // 拖动快
    logTaskUpdate(id, mode, task) {
      this.taskManager(mode, task)
      const text = (task && task.text ? ` (${task.text})` : '')
      const message = `Task ${mode}: ${id} ${text}`
      this.addMessage(message)
    },
    // 变更先
    logLinkUpdate(id, mode, link) {
      this.lineManager(id, mode, link)
      let message = `Link ${mode}: ${id}`
      if (link) {
        message += ` ( source: ${link.source}, target: ${link.target} )`
      }
      this.addMessage(message)
    },
    lineManager(id, mode, link) {
      var flag = true
      var linksTemp = this.$refs.ganttComponents.tasks.links
      if (linksTemp !== undefined && linksTemp !== null && linksTemp !== '' && linksTemp.length > 0 && mode !== 'delete') {
        if (linksTemp.find(obj => obj.source === link.source)) {
          flag = false
        }
      }
      if (flag) {
        var jsonLine = '{"source": "' + link.source + '", "target": "' + link.target + '", "type": "' + link.type + '"}'
        if (mode === 'delete') {
          jsonLine = ''
          this.$refs.ganttComponents.tasks.links.some((item, index) => {
            if (item.source === link.source) {
              this.$refs.ganttComponents.tasks.links.splice(index, 1)
              return true
            }
          })
        }
        updateLieByRowId({ id: link.source, ganttLine: jsonLine }).then(response => {
          if (response.code === 200 || response.data >= 1) {
            this.msgSuccess(this.$t('保存成功'))
          } else {
            this.msgError(this.$t('保存异常'))
          }
        })
      } else {
        this.msgWarning(this.$t('已存在或不合理的导向线!'))
        this.$refs.ganttComponents.deleteLinks(id)
      }
    },
    // 后台更新任务
    taskManager(mode, task) {
      var startDate, endDate
      var dateTime = new Date(task.start_date)
      startDate = dateTime.toLocaleDateString()
      dateTime = dateTime.setDate(dateTime.getDate() + task.duration)
      dateTime = new Date(dateTime)
      endDate = dateTime.toLocaleDateString()
      if (mode === 'create') {
        console.log('create')
        saveDealSupervise({ parentId: '0', dealId: this.currentDealId, estimatedStartTime: new Date(startDate), completionTime: new Date(endDate), itemName: task.text }).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t('保存成功'))
          } else {
            this.msgError(this.$t('保存异常'))
          }
        })
      } else if (mode === 'update') {
        // 修改时间
        updateTimeByRowId({ id: task.rowId, estimatedStartTime: new Date(startDate), completionTime: new Date(endDate) }).then(response => {
          if (response.code === 200 || response.data >= 1) {
            this.msgSuccess(this.$t('保存成功'))
          } else {
            this.msgError(this.$t('保存异常'))
          }
        })
      } else if (mode === 'delete') {
        if (task.rowId !== undefined && task.rowId !== null && task.rowI !== '') {
          delDealSupervise(task.rowId).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('操作成功'))
            } else {
              this.msgError(this.$t('操作异常'))
            }
          })
        }
      }
    },
    addHandler(row) {
      this.formOpen = true
      if (row !== null) {
        row.dealId = this.currentDealId
      }
      this.$nextTick(() => {
        row.id = undefined
        // 调用form页面的 init 方法初始化数据
        this.$refs.dealSuperviseForm.ganttInit(row)
      })
    },
    // 修改form
    updateHandler(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.dealSuperviseForm.ganttInit(row)
      })
    },
    submitFormEnd() {
      this.init(this.currentDealId)
    }
  }
}
</script>

<style scoped>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }

  .container {
    height: 100%;
    width: 100%;
  }

  .left-container {
    overflow: hidden;
    position: relative;
    height: 100%;
    z-index: 1 !important;
  }

  .gantt-messages {
    list-style-type: none;
    height: 50%;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    padding-left: 5px;
  }

  .gantt-messages > .gantt-message {
    background-color: #f4f4f4;
    box-shadow:inset 5px 0 #d69000;
    font-family: Geneva, Arial, Helvetica, sans-serif;
    font-size: 14px;
    margin: 5px 0;
    padding: 8px 0 8px 10px;
  }

  .gantt-selected-info h2 {
    border-bottom: 1px solid #cecece;
  }

  .select-task-prompt h2{
    color: #d9d9d9;
  }

  .fullBtn {
    font-size: 25px;
    position: absolute;
    z-index: 1002;
    right: 3%;
    bottom: 5%;
    cursor: pointer;
  }
  /*/deep/ .v-modal {*/
  /*  z-index: 0 !important;*/
  /*}*/
  /*/deep/ .fixed-header {*/
  /*  z-index: 0 !important;*/
  /*}*/
</style>
